import 'dart:async';
import 'package:aio/aio.dart';
import 'package:flutter/cupertino.dart';
import 'package:app/src/config/app_data_config.dart';
import 'package:app/src/http/bean/wroks/search_bean.dart';
import 'package:app/src/http/bean/http_data.dart';
import 'package:app/src/http/bean/ywx_limit.dart';
import 'package:app/src/http/sign.dart';
import 'package:app/src/http/url.dart';
import 'package:app/src/ui/dialog/dailog.dart';
import '../../manager/ywx_manager.dart';
import '../bean/worksdo/equipment_management_bean.dart';
import '../bean/worksdo/equipment_management_bean.dart';
import '../bean/worksdo/material_requisition_bean.dart';
import '../bean/wroks/dispatchingaudit_bean.dart';

///设备管理：工单中心，我的工单。
class EquipmentManagementModel {
  ///获取工单中心列表；只显示该设备为管理人的，才会有数据。
  ///PageNo 页码,从1开始。(物料请购和设备管理是从1开始的，其他审核列表，是从0开始的)
  ///PageSize 每页显示条目数量
  ///searchInfo 搜索条件
  static Future<AppHttpResult<List<EquipmentInfo>, EquipmentInfo>?>
      GetRepairOrderList(BuildContext context, bool isEnableLoad,
          {String? PageNo,
          String? PageSize = "15",
          SearchInfo? searchInfo}) async {
    Completer completer =
        new Completer<AppHttpResult<List<EquipmentInfo>, EquipmentInfo>?>();
    var url = Url.baseurl() + Url.repairOrder;
    //var url = "http://masapp.zuvowf.com/" + Url.contractdogetlist;//测试服务器访问受限制，数据返回为空。
    var token = AppDataConfig.getToken();
    // searchInfo?.InsertStartDatetime ?? ""; //开始时间;
    // searchInfo?.InsertEndDatetime ?? ""; //结束时间
    // searchInfo?.UserPerson?.PersonId;//保修人员，传 PersonId
    var queryParameters = Map<String, dynamic>();
    queryParameters['type'] = "GetRepairOrderList"; //获取工单中心列表
    var data = EquipmentRequestData();
    data.Code = searchInfo?.DeviceCoding; //设备编码
    data.PageIndex = PageNo; //页码
    data.PageSize = PageSize; //每页显示个数
    // data.PageSize = "1"; //每页显示个数
    data?.StartTime = searchInfo?.InsertStartDatetime ?? ""; //保修开始时间;
    data?.EndTime = searchInfo?.InsertEndDatetime ?? ""; //保修结束时间
    data?.AddPersonId = searchInfo?.UserPerson?.PersonId; //保修人员id
    searchInfo?.searchDatas?.forEach((element) {
      if (element.id == "0") {
        //工单号
        data?.RepairNo = element.showValue;
      } else if (element.id == "1") {
        //等级
        data?.Level = element.data?.key;
      } else if (element.id == "2") {
        //设备名称
        data?.EquipmentName = element.showValue;
      } else if (element.id == "3") {
        //工单类型
        data?.RepairType = element.data?.key;
      }
    });
    queryParameters['data'] = data.jsonEncodeToJson();
    // PrintUtils.printlnLong('搜索数据：${ subData.jsonEncodeToJson()}');
    // PrintUtils.printlnLong('搜索数据：${ searchInfo?.jsonEncodeToJson()}');
    // InsertStartDatetime":"2024-04-16","InsertEndDatetime":"2024-04-16"
    var sign = getSign(queryParameters);
    queryParameters['sign'] = sign;
    //print('签名：$sign');
    KOhttp(url)
      ..isEnableLoad(isEnableLoad, context)
      // ..onStart(() {
      //   print('开始');
      // })
      ..onError((code, error) {
        // print('错误:\t$code\t$error');
        completer.complete(null); //fixme 这里也返回一下；防止列表没有收到回调，一直处于刷新的状态；
        AppDialog.showDialogWithError(context, code, error);
      })
      ..onSuccess((result) {
        // print('数据返回:\n$result');
        // PrintUtils.printlnLong('数据返回:\n$result');
        if (StringUtils.isEmpty(result)) {
          completer.complete(null);
        }
      })
      // ..onFinish(() {
      //   print('结束');
      // })
      ..isCache(false)
      ..addHeader('token', token)
      ..addFormDatas(queryParameters)
      ..contentType = ContentType.form
      ..isEnableLog = AppDataConfig.isEnableLog
      ..postASync<AppHttpResult<List<EquipmentInfo>, EquipmentInfo>>(
              AppHttpResult()
                ..Data = <EquipmentInfo>[]
                ..t2 = EquipmentInfo())
          ?.then((result) {
        completer.complete(result);
      });
    return completer.future
        as Future<AppHttpResult<List<EquipmentInfo>, EquipmentInfo>?>;
  }

  ///获取维修工
  static Future<AppHttpResult<List<MaintenanceManInfo>, MaintenanceManInfo>>
      GetRepairPersonList(
    BuildContext context,
    bool isEnableLoad, {
    ResponseCallbackWithStringCode_? onError = null,
  }) async {
    Completer completer = new Completer<
        AppHttpResult<List<MaintenanceManInfo>, MaintenanceManInfo>>();
    var url = Url.baseurl() + Url.repairOrder; //fixme 目前接口用的是审核类的接口，后面需要重新对接。
    var token = AppDataConfig.getToken();
    var queryParameters = Map<String, dynamic>();
    queryParameters['type'] = "GetRepairPersonList"; //获取维修工
    queryParameters['data'] = AppDataConfig.getFactory()?.FactoryId; //工厂id
    var sign = getSign(queryParameters);
    queryParameters['sign'] = sign;
    //print('签名：$sign');
    KOhttp(url)
      ..isEnableLoad(isEnableLoad, context)
      // ..onStart(() {
      //   print('开始');
      // })
      ..onError((code, error) {
        // print('错误:\t$code\t$error');
        completer.complete(null); //fixme 这里也返回一下；防止列表没有收到回调，一直处于刷新的状态；
        AppDialog.showDialogWithError(context, code, error);
      })
      ..onSuccess((result) {
        // print('数据返回:\n$result');
        // PrintUtils.printlnLong('数据返回:\n$result');
        if (StringUtils.isEmpty(result)) {
          completer.complete(null);
        }
      })
      // ..onFinish(() {
      //   print('结束');
      // })
      ..isCache(false)
      ..addHeader('token', token)
      ..addFormDatas(queryParameters)
      ..contentType = ContentType.form
      ..isEnableLog = AppDataConfig.isEnableLog
      ..onError((code, error) {
        // print('错误:\t$code\t$error');
        if (onError != null) {
          onError?.call(code, error);
        } else {
          AppDialog.showDialogWithError(context, code, error);
        }
      })
      ..postASync<AppHttpResult<List<MaintenanceManInfo>, MaintenanceManInfo>>(
              AppHttpResult()
                ..Data = <MaintenanceManInfo>[]
                ..t2 = MaintenanceManInfo())
          ?.then((result) {
        completer.complete(result);
      });
    return completer.future
        as Future<AppHttpResult<List<MaintenanceManInfo>, MaintenanceManInfo>>;
  }

  ///删除
  ///工单中心列表：删除派单
  static Future<AppHttpResult<String, String>> delRepairOrder(
      BuildContext context, EquipmentInfo? data, bool isEnableLoad) async {
    Completer completer = new Completer<AppHttpResult<String, String>>();
    var url = Url.baseurl() + Url.repairOrder; //fixme 目前接口用的是审核类的接口，后面需要重新对接。
    //var url = "http://masapp.zuvowf.com/" + Url.contractdogetlist;//测试服务器访问受限制，数据返回为空。
    var token = AppDataConfig.getToken();
    // searchInfo?.InsertStartDatetime ?? ""; //开始时间;
    // searchInfo?.InsertEndDatetime ?? ""; //结束时间
    // searchInfo?.UserPerson?.PersonId;//保修人员，传 PersonId
    var queryParameters = Map<String, dynamic>();
    queryParameters['type'] = "DeleteRepairOrder"; //删除工单
    // queryParameters['data'] = data?.jsonEncodeToJson();
    queryParameters['data'] = data?.Id;
    // PrintUtils.printlnLong('搜索数据：${ subData.jsonEncodeToJson()}');
    // PrintUtils.printlnLong('搜索数据：${ searchInfo?.jsonEncodeToJson()}');
    // InsertStartDatetime":"2024-04-16","InsertEndDatetime":"2024-04-16"
    var sign = getSign(queryParameters);
    queryParameters['sign'] = sign;
    //print('签名：$sign');
    KOhttp(url)
      ..isEnableLoad(isEnableLoad, context)
      // ..onStart(() {
      //   print('开始');
      // })
      ..onError((code, error) {
        // print('错误:\t$code\t$error');
        completer.complete(null); //fixme 这里也返回一下；防止列表没有收到回调，一直处于刷新的状态；
        AppDialog.showDialogWithError(context, code, error);
      })
      ..onSuccess((result) {
        // {"Res":true,"MsgCode":"100","MsgDetail":"","Data":"","TotalRowCount":0}
        // print('派工数据返回:\n$result');
        // PrintUtils.printlnLong('工单删除数据返回:\n$result');
        if (StringUtils.isEmpty(result)) {
          completer.complete(null);
        }
      })
      // ..onFinish(() {
      //   print('结束');
      // })
      ..isCache(false)
      ..addHeader('token', token)
      ..addFormDatas(queryParameters)
      ..contentType = ContentType.form
      ..isEnableLog = AppDataConfig.isEnableLog
      ..postASync<AppHttpResult<String, String>>(AppHttpResult()
            ..Data = ""
            ..t2 = "")
          ?.then((result) {
        completer.complete(result);
      });
    return completer.future as Future<AppHttpResult<String, String>>;
  }

  ///提交
  ///工单中心：派单
  static Future<AppHttpResult<String, String>> DispatchingRepairOrder(
      BuildContext context,
      EquipmentResponseData? data,
      bool isEnableLoad) async {
    Completer completer = new Completer<AppHttpResult<String, String>>();
    var url = Url.baseurl() + Url.repairOrder; //fixme 目前接口用的是审核类的接口，后面需要重新对接。
    //var url = "http://masapp.zuvowf.com/" + Url.contractdogetlist;//测试服务器访问受限制，数据返回为空。
    var token = AppDataConfig.getToken();
    // searchInfo?.InsertStartDatetime ?? ""; //开始时间;
    // searchInfo?.InsertEndDatetime ?? ""; //结束时间
    // searchInfo?.UserPerson?.PersonId;//保修人员，传 PersonId
    var queryParameters = Map<String, dynamic>();
    queryParameters['type'] = "DispatchingRepairOrder"; //派单
    queryParameters['data'] = data?.jsonEncodeToJson();
    // PrintUtils.printlnLong('搜索数据：${ subData.jsonEncodeToJson()}');
    // PrintUtils.printlnLong('搜索数据：${ searchInfo?.jsonEncodeToJson()}');
    // InsertStartDatetime":"2024-04-16","InsertEndDatetime":"2024-04-16"
    var sign = getSign(queryParameters);
    queryParameters['sign'] = sign;
    //print('签名：$sign');
    KOhttp(url)
      ..isEnableLoad(isEnableLoad, context)
      // ..onStart(() {
      //   print('开始');
      // })
      ..onError((code, error) {
        // print('错误:\t$code\t$error');
        completer.complete(null); //fixme 这里也返回一下；防止列表没有收到回调，一直处于刷新的状态；
        AppDialog.showDialogWithError(context, code, error);
      })
      ..onSuccess((result) {
        // {"Res":true,"MsgCode":"100","MsgDetail":"","Data":"","TotalRowCount":0}
        // print('派工数据返回:\n$result');
        // PrintUtils.printlnLong('数据返回:\n$result');
        if (StringUtils.isEmpty(result)) {
          completer.complete(null);
        }
      })
      // ..onFinish(() {
      //   print('结束');
      // })
      ..isCache(false)
      ..addHeader('token', token)
      ..addFormDatas(queryParameters)
      ..contentType = ContentType.form
      ..isEnableLog = AppDataConfig.isEnableLog
      ..postASync<AppHttpResult<String, String>>(AppHttpResult()
            ..Data = ""
            ..t2 = "")
          ?.then((result) {
        completer.complete(result);
      });
    return completer.future as Future<AppHttpResult<String, String>>;
  }

  ///获取我的工单列表
  ///PageNo 页码,从1开始。(物料请购和设备管理是从1开始的，其他审核列表，是从0开始的)
  ///PageSize 每页显示条目数量
  ///searchInfo 搜索条件
  static Future<AppHttpResult<List<EquipmentInfo>, EquipmentInfo>?>
      GetMyRepairOrder(BuildContext context, bool isEnableLoad,
          {String? PageNo,
          String? PageSize = "15",
          SearchInfo? searchInfo}) async {
    Completer completer =
        new Completer<AppHttpResult<List<EquipmentInfo>, EquipmentInfo>?>();
    var url = Url.baseurl() + Url.repairOrder;
    //var url = "http://masapp.zuvowf.com/" + Url.contractdogetlist;//测试服务器访问受限制，数据返回为空。
    var token = AppDataConfig.getToken();
    // searchInfo?.InsertStartDatetime ?? ""; //开始时间;
    // searchInfo?.InsertEndDatetime ?? ""; //结束时间
    // searchInfo?.UserPerson?.PersonId;//保修人员，传 PersonId
    var queryParameters = Map<String, dynamic>();
    queryParameters['type'] = "GetMyRepairOrder"; //获取我的工单列表
    var data = EquipmentRequestData();
    data.Code = searchInfo?.DeviceCoding; //设备编码
    data.PageIndex = PageNo; //页码
    data.PageSize = PageSize; //每页显示个数
    // data.PageSize = "1"; //每页显示个数
    data?.StartTime = searchInfo?.InsertStartDatetime ?? ""; //开始时间;
    data?.BeginTime = searchInfo?.InsertStartDatetime ?? ""; //开始时间;
    data?.EndTime = searchInfo?.InsertEndDatetime ?? ""; //结束时间
    data?.AddPersonId = searchInfo?.UserPerson?.PersonId; //保修人员id
    searchInfo?.searchDatas?.forEach((element) {
      if (element.id == "0") {
        //工单号
        data?.RepairNo = element.showValue;
      } else if (element.id == "1") {
        //等级
        data?.Level = element.data?.key;
      } else if (element.id == "2") {
        //设备名称
        data?.EquipmentName = element.showValue;
      } else if (element.id == "3") {
        //工单类型
        data?.RepairType = element.data?.key;
      }
    });
    queryParameters['data'] = data.jsonEncodeToJson();
    // PrintUtils.printlnLong('搜索数据：${ subData.jsonEncodeToJson()}');
    // PrintUtils.printlnLong('搜索数据：${ searchInfo?.jsonEncodeToJson()}');
    // InsertStartDatetime":"2024-04-16","InsertEndDatetime":"2024-04-16"
    var sign = getSign(queryParameters);
    queryParameters['sign'] = sign;
    //print('签名：$sign');
    KOhttp(url)
      ..isEnableLoad(isEnableLoad, context)
      // ..onStart(() {
      //   print('开始');
      // })
      ..onError((code, error) {
        // print('错误:\t$code\t$error');
        completer.complete(null); //fixme 这里也返回一下；防止列表没有收到回调，一直处于刷新的状态；
        AppDialog.showDialogWithError(context, code, error);
      })
      ..onSuccess((result) {
        // print('数据返回:\n$result');
        // PrintUtils.printlnLong('数据返回:\n$result');
        if (StringUtils.isEmpty(result)) {
          completer.complete(null);
        }
      })
      // ..onFinish(() {
      //   print('结束');
      // })
      ..isCache(false)
      ..addHeader('token', token)
      ..addFormDatas(queryParameters)
      ..contentType = ContentType.form
      ..isEnableLog = AppDataConfig.isEnableLog
      ..postASync<AppHttpResult<List<EquipmentInfo>, EquipmentInfo>>(
              AppHttpResult()
                ..Data = <EquipmentInfo>[]
                ..t2 = EquipmentInfo())
          ?.then((result) {
        completer.complete(result);
      });
    return completer.future
        as Future<AppHttpResult<List<EquipmentInfo>, EquipmentInfo>?>;
  }

  ///获取我的工单详情
  static Future<AppHttpResult<GetMyRepairOrderInfoBean, String>>
      GetMyRepairOrderInfo(
    BuildContext context,
    EquipmentInfo equipmentInfo,
    bool isEnableLoad, {
    ResponseCallbackWithStringCode_? onError = null,
  }) async {
    Completer completer =
        new Completer<AppHttpResult<GetMyRepairOrderInfoBean, String>>();
    var url = Url.baseurl() + Url.repairOrder; //fixme 目前接口用的是审核类的接口，后面需要重新对接。
    var token = AppDataConfig.getToken();
    var queryParameters = Map<String, dynamic>();
    queryParameters['type'] = "GetMyRepairOrderInfo"; //我的工单详情
    queryParameters['data'] = equipmentInfo.Id; //id
    var sign = getSign(queryParameters);
    queryParameters['sign'] = sign;
    //print('签名：$sign');
    KOhttp(url)
      ..isEnableLoad(isEnableLoad, context)
      // ..onStart(() {
      //   print('开始');
      // })
      ..onError((code, error) {
        // print('错误:\t$code\t$error');
        completer.complete(null); //fixme 这里也返回一下；防止列表没有收到回调，一直处于刷新的状态；
        AppDialog.showDialogWithError(context, code, error);
      })
      ..onSuccess((result) {
        // print('数据返回:\n$result');
        // PrintUtils.printlnLong('我的工单详情数据返回:\n$result');
        if (StringUtils.isEmpty(result)) {
          completer.complete(null);
        }
      })
      // ..onFinish(() {
      //   print('结束');
      // })
      ..isCache(false)
      ..addHeader('token', token)
      ..addFormDatas(queryParameters)
      ..contentType = ContentType.form
      ..isEnableLog = AppDataConfig.isEnableLog
      ..onError((code, error) {
        // print('错误:\t$code\t$error');
        if (onError != null) {
          onError?.call(code, error);
        } else {
          AppDialog.showDialogWithError(context, code, error);
        }
      })
      ..postASync<AppHttpResult<GetMyRepairOrderInfoBean, String>>(
              AppHttpResult()
                ..Data = GetMyRepairOrderInfoBean()
                ..t2 = "")
          ?.then((result) {
        completer.complete(result);
      });
    return completer.future
        as Future<AppHttpResult<GetMyRepairOrderInfoBean, String>>;
  }

  ///提交
  ///我的工单：接单
  static Future<AppHttpResult<String, String>> ConfirmRepairOrder(
      BuildContext context,
      EquipmentResponseData? data,
      bool isEnableLoad) async {
    Completer completer = new Completer<AppHttpResult<String, String>>();
    var url = Url.baseurl() + Url.repairOrder; //fixme 目前接口用的是审核类的接口，后面需要重新对接。
    //var url = "http://masapp.zuvowf.com/" + Url.contractdogetlist;//测试服务器访问受限制，数据返回为空。
    var token = AppDataConfig.getToken();
    // searchInfo?.InsertStartDatetime ?? ""; //开始时间;
    // searchInfo?.InsertEndDatetime ?? ""; //结束时间
    // searchInfo?.UserPerson?.PersonId;//保修人员，传 PersonId
    var queryParameters = Map<String, dynamic>();
    queryParameters['type'] = "ConfirmRepairOrder"; //接单
    queryParameters['data'] = data?.equipmentInfo?.Id; //工单id
    // PrintUtils.printlnLong('搜索数据：${ subData.jsonEncodeToJson()}');
    // PrintUtils.printlnLong('搜索数据：${ searchInfo?.jsonEncodeToJson()}');
    // InsertStartDatetime":"2024-04-16","InsertEndDatetime":"2024-04-16"
    var sign = getSign(queryParameters);
    queryParameters['sign'] = sign;
    //print('签名：$sign');
    KOhttp(url)
      ..isEnableLoad(isEnableLoad, context)
      // ..onStart(() {
      //   print('开始');
      // })
      ..onError((code, error) {
        // print('错误:\t$code\t$error');
        completer.complete(null); //fixme 这里也返回一下；防止列表没有收到回调，一直处于刷新的状态；
        AppDialog.showDialogWithError(context, code, error);
      })
      ..onSuccess((result) {
        // {"Res":true,"MsgCode":"100","MsgDetail":"","Data":"","TotalRowCount":0}
        // print('派工数据返回:\n$result');
        // {"Res":false,"MsgCode":"0","MsgDetail":"您已接过单","Data":null,"TotalRowCount":0}
        // PrintUtils.printlnLong('接单数据返回:\n$result');
        if (StringUtils.isEmpty(result)) {
          completer.complete(null);
        }
      })
      // ..onFinish(() {
      //   print('结束');
      // })
      ..isCache(false)
      ..addHeader('token', token)
      ..addFormDatas(queryParameters)
      ..contentType = ContentType.form
      ..isEnableLog = AppDataConfig.isEnableLog
      ..postASync<AppHttpResult<String, String>>(AppHttpResult()
            ..Data = ""
            ..t2 = "")
          ?.then((result) {
        completer.complete(result);
      });
    return completer.future as Future<AppHttpResult<String, String>>;
  }

  ///提交
  ///我的工单：完工
  static Future<AppHttpResult<String, String>> CompleteRepairOrder(
      BuildContext context,
      EquipmentResponseData? data,
      bool isEnableLoad) async {
    Completer completer = new Completer<AppHttpResult<String, String>>();
    var url = Url.baseurl() + Url.repairOrder; //fixme 目前接口用的是审核类的接口，后面需要重新对接。
    //var url = "http://masapp.zuvowf.com/" + Url.contractdogetlist;//测试服务器访问受限制，数据返回为空。
    var token = AppDataConfig.getToken();
    var queryParameters = Map<String, dynamic>();
    queryParameters['type'] = "CompleteRepairOrder"; //接单
    // queryParameters['data'] = data?.equipmentInfo?.Id; //工单id
    queryParameters['data'] = data?.jsonEncodeToJson();
    // PrintUtils.printlnLong('搜索数据：${ subData.jsonEncodeToJson()}');
    // PrintUtils.printlnLong('搜索数据：${ searchInfo?.jsonEncodeToJson()}');
    // InsertStartDatetime":"2024-04-16","InsertEndDatetime":"2024-04-16"
    var sign = getSign(queryParameters);
    queryParameters['sign'] = sign;
    //print('签名：$sign');
    KOhttp(url)
      ..isEnableLoad(isEnableLoad, context)
      // ..onStart(() {
      //   print('开始');
      // })
      ..onError((code, error) {
        // print('错误:\t$code\t$error');
        completer.complete(null); //fixme 这里也返回一下；防止列表没有收到回调，一直处于刷新的状态；
        AppDialog.showDialogWithError(context, code, error);
      })
      ..onSuccess((result) {
        // {"Res":true,"MsgCode":"100","MsgDetail":"","Data":"","TotalRowCount":0}
        // print('派工数据返回:\n$result');
        // {"Res":false,"MsgCode":"0","MsgDetail":"您已接过单","Data":null,"TotalRowCount":0}
        // PrintUtils.printlnLong('完工数据返回:\n$result');
        if (StringUtils.isEmpty(result)) {
          completer.complete(null);
        }
      })
      // ..onFinish(() {
      //   print('结束');
      // })
      ..isCache(false)
      ..addHeader('token', token)
      ..addFormDatas(queryParameters)
      ..contentType = ContentType.form
      ..isEnableLog = AppDataConfig.isEnableLog
      ..postASync<AppHttpResult<String, String>>(AppHttpResult()
            ..Data = ""
            ..t2 = "")
          ?.then((result) {
        completer.complete(result);
      });
    return completer.future as Future<AppHttpResult<String, String>>;
  }
}
